<template>
  <div class="permission-management">
    <el-card>
      <div class="section-title">权限管理</div>
      
      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="权限名称">
            <el-input 
              v-model="filterForm.name" 
              placeholder="请输入权限名称" 
              clearable
              style="width: 200px;"
              class="center-input"
            />
          </el-form-item>
          <el-form-item label="权限代码">
            <el-input 
              v-model="filterForm.code" 
              placeholder="请输入权限代码" 
              clearable
              style="width: 200px;"
              class="center-input"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="filterForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px;"
              class="center-input"
            >
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item label="权限类型">
            <el-select 
              v-model="filterForm.type" 
              placeholder="请选择类型" 
              clearable
              style="width: 150px;"
              :loading="typeOptionsLoading"
              class="center-input"
            >
              <el-option 
                v-for="type in permissionTypeOptions" 
                :key="type.value" 
                :label="type.label" 
                :value="type.value" 
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              筛选
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
              <el-button 
          type="primary" 
          style="margin-bottom: 16px;" 
          @click="openAddDialog"
        >
          <el-icon style="margin-right: 4px;"><Plus /></el-icon>
          新增权限
        </el-button>
      
      <!-- 数据区域 -->
      <div class="data-area">
        <template v-if="loading">
          <el-skeleton :rows="6" animated style="margin: 32px 0;" />
        </template>
        <template v-else>
          <el-table 
            :row-key="(row,index)=>row.id || index" 
            :data="permissionList" 
            style="width: 100%"  
            :loading="loading"
            :max-height="500"
          >
            <el-table-column prop="Index" label="序号" min-width="80" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="权限名称" min-width="200" align="center">
              <template #default="scope">
                <el-input v-if="editingRowId === scope.row.id" v-model="scope.row.name" placeholder="请输入权限名称" class="center-input" />
                <span v-else>{{ scope.row.name || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="权限代码" min-width="200" align="center">
              <template #default="scope">
                <el-input v-if="editingRowId === scope.row.id" v-model="scope.row.code" placeholder="请输入权限代码" class="center-input" />
                <span v-else>{{ scope.row.code || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="300" align="center">
              <template #default="scope">
                <el-input v-if="editingRowId === scope.row.id" v-model="scope.row.description" placeholder="请输入描述" class="center-input" />
                <span v-else>{{ scope.row.description || '' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isActive" label="状态" min-width="100" align="center">
              <template #default="scope">
                <template v-if="editingRowId === scope.row.id">
                  <el-switch v-model="scope.row.isActive" />
                </template>
                <template v-else>
                  <el-tag v-if="scope.row.isActive === true" type="success">启用</el-tag>
                  <el-tag v-else type="danger">禁用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="200" align="center">
              <template #default="scope">
                <template v-if="editingRowId !== scope.row.id">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="openEdit(scope.row.id)" 
                    link
                  >
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="openDelete(scope.row.id)" 
                    link
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
                <template v-else>
                  <el-button type="success" size="small" @click="saveEdit(scope.row.id)" link>
                    <el-icon><Check /></el-icon>
                    保存
                  </el-button>
                  <el-button type="warning" size="small" @click="cancelEdit()" link>
                    <el-icon><Close /></el-icon>
                    取消
                  </el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <template v-if="loading">
          <el-skeleton :rows="1" animated style="width: 400px; height: 50px;" />
        </template>
        <template v-else>
          <el-pagination
            :background="background"
            layout="sizes, prev, pager, next, jumper"
            :total="totalSize"
            v-model:current-page="currentPage.page"
            v-model:page-size="currentPage.pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :disabled="false"
          />
        </template>
      </div>
    </el-card>

    <!-- 新增权限对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增权限" width="500px" :close-on-click-modal="false">
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="80px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="addForm.code" placeholder="例如: permission.manage" clearable />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addForm.description" placeholder="请输入描述" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false" size="large">取消</el-button>
          <el-button type="primary" @click="handleAdd" size="large" :loading="addLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除权限"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="delete-confirm">
        <div class="delete-icon">
          <el-icon size="48" color="#f56c6c"><Warning /></el-icon>
        </div>
        <div class="delete-message">
          <h3>确定要删除该权限吗？</h3>
          <p>此操作不可恢复，请谨慎操作。</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false" size="large">取消</el-button>
          <el-button type="danger" @click="handleDelete" size="large" :loading="deleteLoading">删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 定义组件名称
defineOptions({
  name: 'PermissionIndex'
})

import { ref, onMounted } from 'vue'
import { Edit, Delete, Check, Close, Warning, Search, Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { handleApiError } from '@/utils/errorHandler'
import {
    getPermissionList,
    addPermission,
    updatePermission,
    deletePermission,
    enablePermission,
    disablePermission
} from '@/api/permission'

// 响应式数据
const permissionList = ref([])
const loading = ref(false)
const currentPage = ref({ page: 1, pageSize: 10 })
const totalSize = ref(0)
const background = ref(true)

// 新增对话框相关
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = ref({ name: '', code: '', description: '' })
const addLoading = ref(false)
const rules = {
    name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入权限代码', trigger: 'blur' }],
    description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
}

// 编辑相关
const editingRowId = ref(null)
let backupRow = null

// 删除相关
const deleteDialogVisible = ref(false)
const deleteLoading = ref(false)
let deleteId = null

// 筛选相关
const filterForm = ref({
    name: '',
    code: '',
    status: '',
    type: ''
})

// 权限类型选项相关
const permissionTypeOptions = ref([])
const typeOptionsLoading = ref(false)

/**
 * 根据权限代码获取权限类型
 */
function getPermissionType(permissionCode) {
    if (!permissionCode) return '';
    
    // 根据权限代码的前缀判断类型
    const code = permissionCode.toLowerCase();
    if (code.startsWith('menu.')) return 'menu';
    if (code.startsWith('system.')) return 'system';
    if (code.startsWith('permission.')) return 'permission';
    if (code.startsWith('role.')) return 'role';
    if (code.startsWith('file.')) return 'file';
    if (code.startsWith('user.')) return 'user';
    if (code.startsWith('log.')) return 'log';
    
    return 'other';
}

/**
 * 从权限数据中提取类型选项
 */
function extractPermissionTypes(permissions) {
    const typeMap = {
        'menu': '菜单权限',
        'system': '系统权限',
        'permission': '权限管理',
        'role': '角色权限',
        'file': '文件权限',
        'user': '用户权限',
        'log': '日志权限',
        'other': '其他权限'
    };
    
    const types = new Set();
    permissions.forEach(permission => {
        const type = getPermissionType(permission.code);
        if (type) {
            types.add(type);
        }
    });
    
    return Array.from(types).map(type => ({
        value: type,
        label: typeMap[type] || type
    })).sort((a, b) => {
        // 按优先级排序
        const priority = { 'menu': 1, 'system': 2, 'permission': 3, 'role': 4, 'file': 5, 'user': 6, 'log': 7, 'other': 8 };
        return (priority[a.value] || 999) - (priority[b.value] || 999);
    });
}

/**
 * 获取权限列表
 */
async function getPermissions(showLoading = true) {
    try {
        if (showLoading) {
            loading.value = true
        }
        
        // 获取所有权限数据，不传递筛选参数
        const apiParams = {
            page: 1,
            size: 1000 // 获取所有数据，在前端进行筛选
        };
        
        const response = await getPermissionList(apiParams)
        
        // 处理API响应数据
        if (response && response.code === 200) {
            let allPermissions = [];
            
            if (response.data && response.data.items && Array.isArray(response.data.items)) {
                allPermissions = response.data.items;
            } else if (response.data && Array.isArray(response.data)) {
                allPermissions = response.data;
            } else {
                allPermissions = [];
            }
            
            // 在前端进行筛选
            let filteredPermissions = allPermissions.filter(permission => {
                // 权限名称筛选
                if (filterForm.value.name && !permission.name.toLowerCase().includes(filterForm.value.name.toLowerCase())) {
                    return false;
                }
                
                // 权限代码筛选
                if (filterForm.value.code && !permission.code.toLowerCase().includes(filterForm.value.code.toLowerCase())) {
                    return false;
                }
                
                // 状态筛选
                if (filterForm.value.status) {
                    const permissionStatus = permission.isActive ? 'active' : 'inactive';
                    if (permissionStatus !== filterForm.value.status) {
                        return false;
                    }
                }
                
                // 权限类型筛选
                if (filterForm.value.type) {
                    const permissionType = getPermissionType(permission.code);
                    if (permissionType !== filterForm.value.type) {
                        return false;
                    }
                }
                
                return true;
            });
            
            // 更新权限类型选项
            permissionTypeOptions.value = extractPermissionTypes(allPermissions);
            
            // 分页处理
            const startIndex = (currentPage.value.page - 1) * currentPage.value.pageSize;
            const endIndex = startIndex + currentPage.value.pageSize;
            permissionList.value = filteredPermissions.slice(startIndex, endIndex);
            totalSize.value = filteredPermissions.length;
            
        } else {
            permissionList.value = []
            totalSize.value = 0
            if (response && response.message) {
                ElMessage.error(response.message)
            }
        }
    } catch (error) {
        console.error('获取权限列表失败:', error)
        permissionList.value = []
        totalSize.value = 0
        handleApiError(error, { showMessage: true })
    } finally {
        if (showLoading) {
            loading.value = false
        }
    }
}

/**
 * 处理筛选
 */
function handleFilter() {
    currentPage.value.page = 1
    getPermissions()
}

/**
 * 重置筛选
 */
function resetFilter() {
    filterForm.value = {
        name: '',
        code: '',
        status: '',
        type: ''
    }
    currentPage.value.page = 1
    getPermissions()
}

/**
 * 打开新增对话框
 */
function openAddDialog() {
    addDialogVisible.value = true
    addForm.value = { name: '', code: '', description: '' }
}

/**
 * 处理新增权限
 */
async function handleAdd() {
    try {
        await addFormRef.value.validate()
        addLoading.value = true
        
        const permissionData = {
            name: addForm.value.name,
            code: addForm.value.code,
            description: addForm.value.description
        }
        
        const response = await addPermission(permissionData)
        
        if (response && response.code === 200) {
            ElMessage.success('新增权限成功')
            addDialogVisible.value = false
            await getPermissions()
        } else if (response && response.code === 409) {
            ElMessage.error('权限已经存在')
        } else {
            handleApiError({ response: { status: 400, data: { message: '新增权限失败' } } }, { showMessage: true })
        }
    } catch (error) {
        console.error('新增权限失败:', error)
        handleApiError(error, { showMessage: true })
    } finally {
        addLoading.value = false
    }
}

/**
 * 打开编辑模式
 */
function openEdit(id) {
    editingRowId.value = id
    const row = permissionList.value.find(item => item.id === id)
    if (row) {
        backupRow = { ...row }
    }
}

/**
 * 保存编辑
 */
async function saveEdit(id) {
    try {
        const row = permissionList.value.find(item => item.id === id)
        if (!row) return
        
        // 先更新基本信息
        const response = await updatePermission(id, {
            name: row.name,
            code: row.code,
            description: row.description
        })
        
        if (response && response.code === 200) {
            // 如果状态有变化，调用相应的启用/禁用API
            if (backupRow && backupRow.isActive !== row.isActive) {
                const statusResponse = row.isActive 
                    ? await enablePermission(id)
                    : await disablePermission(id)
                
                if (statusResponse && statusResponse.code === 200) {
                    ElMessage.success('更新权限成功')
                } else {
                    ElMessage.warning('基本信息更新成功，但状态更新失败')
                }
            } else {
                ElMessage.success('更新权限成功')
            }
            
            editingRowId.value = null
            backupRow = null
            await getPermissions()
        } else {
            handleApiError({ response: { status: 400, data: { message: '更新权限失败' } } }, { showMessage: true })
        }
    } catch (error) {
        console.error('更新权限失败:', error)
        handleApiError(error, { showMessage: true })
    }
}

/**
 * 取消编辑
 */
function cancelEdit() {
    if (backupRow) {
        const index = permissionList.value.findIndex(item => item.id === editingRowId.value)
        if (index !== -1) {
            permissionList.value[index] = { ...backupRow }
        }
    }
    editingRowId.value = null
    backupRow = null
}

/**
 * 打开删除对话框
 */
function openDelete(id) {
    deleteId = id
    deleteDialogVisible.value = true
}

/**
 * 处理删除权限
 */
async function handleDelete() {
    try {
        deleteLoading.value = true
        const response = await deletePermission(deleteId)
        
        if (response && response.code === 200) {
            ElMessage.success('删除权限成功')
            deleteDialogVisible.value = false
            await getPermissions()
        } else {
            handleApiError({ response: { status: 400, data: { message: '删除权限失败' } } }, { showMessage: true })
        }
    } catch (error) {
        console.error('删除权限失败:', error)
        handleApiError(error, { showMessage: true })
    } finally {
        deleteLoading.value = false
    }
}

/**
 * 处理分页大小变更
 */
function handleSizeChange(size) {
    currentPage.value.pageSize = size
    currentPage.value.page = 1
    // 分页切换时不显示加载动画
    getPermissions(false)
}

/**
 * 处理当前页变更
 */
function handleCurrentChange(page) {
    currentPage.value.page = page
    // 分页切换时不显示加载动画
    getPermissions(false)
}

// 页面加载时获取数据
onMounted(() => {
    loading.value = true
    getPermissions()
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 18px;
  color: #303133;
}

/* 确保表格可以滚动 */
.el-table__body-wrapper {
  overflow-y: auto !important;
}

.el-table__body {
  overflow: visible !important;
}

/* 数据区域样式 */
.data-area {
  flex: 1;
  overflow: visible;
  padding-right: 10px;
  padding-bottom: 0;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.data-area .el-table {
  width: 100%;
  height: auto;
  overflow: visible;
  margin-bottom: 0;
  border: none;
}

.data-area .el-table__body-wrapper {
  overflow-y: auto;
  max-height: 500px;
}

/* 分页区域样式 */
.pagination-area {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 0;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  min-height: 60px;
  width: 100%;
  position: relative;
  z-index: 10;
  margin-top: 8px;
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  justify-content: flex-start;
  margin: 0;
}

.filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.filter-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
  padding-right: 8px;
}

.filter-form .el-input__wrapper {
  border-radius: 4px;
  border-color: #dcdfe6;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.filter-form .el-input__wrapper:hover {
  border-color: #c0c4cc;
}

.filter-form .el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff inset;
}

.filter-form .el-select .el-input__wrapper {
  border-radius: 4px;
  border-color: #dcdfe6;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.filter-form .el-select .el-input__wrapper:hover {
  border-color: #c0c4cc;
}

.filter-form .el-select .el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff inset;
}

.filter-form .el-button {
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.filter-form .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.filter-form .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.filter-form .el-button--default {
  background-color: #ffffff;
  border-color: #dcdfe6;
  color: #606266;
}

.filter-form .el-button--default:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
.el-table {
  font-size: 14px;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

/* 按钮样式 */
.el-button--small {
  font-size: 12px;
  padding: 5px 11px;
}

/* 标签样式 */
.el-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  background: #fff !important;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 20px 15px;
  background: #fff !important;
}

:deep(.el-dialog__body) {
  padding: 20px;
  background: #fff !important;
}

:deep(.el-dialog__footer) {
  border-top: none;
  padding: 15px 20px 20px;
  background: #fff !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 18px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 输入框样式 */
.el-input__inner {
  border-radius: 4px;
}

/* 新增权限对话框输入框样式 */
:deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

:deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

:deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

:deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 开关样式 */
.el-switch {
  margin: 0;
}

/* 加载状态 */
.el-skeleton {
  margin: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .permission-management {
    padding: 10px;
  }
  
  .section-title {
    font-size: 16px;
  }
  
  .data-area {
    padding-right: 5px;
  }
}



/* 删除确认对话框样式 */
.delete-confirm {
  text-align: center;
  padding: 20px 0;
}

.delete-icon {
  margin-bottom: 16px;
}

.delete-message h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.delete-message p {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

/* 表格样式优化 */
.data-area .el-table {
  border: none;
}

.data-area .el-table th.el-table__cell {
  border-right: none;
  border-bottom: 1px solid #ebeef5;
}

.data-area .el-table td.el-table__cell {
  border-right: none;
  border-bottom: 1px solid #ebeef5;
}

.data-area .el-table--border {
  border: none;
}

.data-area .el-table--border::after {
  display: none;
}

.data-area .el-table--border .el-table__inner-wrapper::after {
  display: none;
}

.data-area .el-table--border .el-table__border-left-patch {
  display: none;
}

/* 表格内输入框居中样式 */
.center-input :deep(.el-input__inner) {
  text-align: center !important;
}

/* 确保编辑状态下的输入框内容居中 */
.data-area .el-table .center-input :deep(.el-input__inner) {
  text-align: center !important;
}
</style>